package edu.zjucst.spb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.zjucst.spb.dao.mapper.SelfActivityMapper;
import edu.zjucst.spb.dao.user.UserDao;
import edu.zjucst.spb.domain.entity.SpbUser;
import edu.zjucst.spb.domain.param.activity.AddBranchActivityParam;
import edu.zjucst.spb.domain.param.activity.AddSelfActivityParam;
import edu.zjucst.spb.domain.param.activity.GetSelfActivityParam;
import edu.zjucst.spb.domain.entity.SelfActivity;
import edu.zjucst.spb.domain.vo.MySelfActivityVO;
import edu.zjucst.spb.service.SelfActivityService;
import edu.zjucst.spb.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 自主活动相关服务实现类
 *
 * @author qingo
 * @since 2023-04-18
 */
@Service
public class SelfActivityServiceImpl extends ServiceImpl<SelfActivityMapper, SelfActivity> implements SelfActivityService {

    @Autowired
    private SelfActivityMapper selfActivityMapper;

    @Autowired
    private UserDao userDao;

    @Override
    public void addSelfActivity(AddSelfActivityParam dto) {
        SelfActivity activity = dto.transform();
        // 新增
        if (dto.getId() == null) {
            // 目前采取前端传入用户学工号，也可从session中取用户学工号
            Long userId = SessionUtil.getUserId();
            activity.setUserNumber(userDao.selectById(userId).getUserNumber());
//            activity.setUserNumber("22151110");
            activity.setAuditStatus("已提交");
            activity.setCreateTime(DateUtil.toLocalDateTime(new Date()));
            activity.setUpdateTime(DateUtil.toLocalDateTime(new Date()));
            selfActivityMapper.insert(activity);
        } else {
            //修改
            activity.setUpdateTime(DateUtil.toLocalDateTime(new Date()));
            selfActivityMapper.updateById(activity);
        }
    }

    @Override
    public List<MySelfActivityVO> getMySelfActivityByPage(GetSelfActivityParam dto) {
        QueryWrapper<SelfActivity> queryWrapper = new QueryWrapper<SelfActivity>();

        if (dto.getStudyYear() != null) {
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.set(dto.getStudyYear(), 1, 1);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.set(dto.getStudyYear() + 1, 1, 1);
            queryWrapper.ge("activity_date", startCalendar.getTime());
            queryWrapper.lt("activity_date", endCalendar.getTime());
        }
        if (StrUtil.isNotBlank(dto.getActivityName())) {
            queryWrapper.like("activity_name", dto.getActivityName());
        }
        if (StrUtil.isNotBlank(dto.getAuditStatus())) {
            queryWrapper.eq("audit_status", dto.getAuditStatus());
        }
        //目前采取前端传入用户学工号，也可从用户token中取用户学工号
        Long userId = SessionUtil.getUserId();
        String userNumber = userDao.selectById(userId).getUserNumber();
        queryWrapper.eq("user_number",userNumber);
//        queryWrapper.eq("user_number", "22151110");
        //TODO 分页
        List<SelfActivity> activities = selfActivityMapper.selectList(queryWrapper);
        return activities.stream().map((x) -> {
            MySelfActivityVO vo = new MySelfActivityVO();
            BeanUtil.copyProperties(x, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void addBranchActivity(AddBranchActivityParam dto) {
        AtomicInteger count = new AtomicInteger();
        dto.getUserNumbers().forEach((user) -> {
            Long hasUser = userDao.selectCount(new QueryWrapper<SpbUser>()
                .eq("user_number", user));
            if (Objects.equals(hasUser, 0L)) {
                return;
            }
            SelfActivity activity = dto.transform(user);
            activity.setAuditStatus("已参与");
            activity.setCreateTime(DateUtil.toLocalDateTime(new Date()));
            activity.setUpdateTime(DateUtil.toLocalDateTime(new Date()));
            if (selfActivityMapper.insert(activity) == 1) {
                count.getAndIncrement();
            }
            return;
        });
        if (count.get() != dto.getUserNumbers().size()) {
            throw new RuntimeException("插入条数不一致！");
        }
    }
}
